package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.*;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Program: health_parent
 * @Description:
 * @Author: choulan
 * @Date:2020-11-16 14:47
 **/
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private LogDao logDao;
    //根据用户名查询用户的角色信息以及对应的权限信息
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if(user==null){
            return null;
        }
        //查询用户角色信息
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);//用户关联权限
            role.setPermissions(permissions);
        }
        user.setRoles(roles);//用户关联角色
        return user;//成功查询到则返回user对象
    }
    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //获取到分页参数
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //使用分页插件
        PageHelper.startPage(currentPage,pageSize);
        //将查询到的数据封装到Page对象中
        Page<User> page= userDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<User> rows = page.getResult();
        return new PageResult(total,rows);
    }
    //添加用户
    @Override
    public void add(User user, Integer[] roleIds) {
        //添加一个User
        userDao.add(user);
        //获得新添加用户的id
        Integer userId = user.getId();
        //添加用户-角色关联
        this.setUserRoleAssociation(userId,roleIds);
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        Set<Role> roles = roleDao.findByUserId(id);
        List<Integer> list=new ArrayList<>();
        if(roles!=null&&roles.size()>0){
            for (Role role : roles) {
                list.add(role.getId());
            }
        }
        return list;
    }

    @Override
    public void edit(User user, Integer[] roleIds) {
        //编辑角色信息
        userDao.edit(user);
        Integer userId = user.getId();
        //清除user-role关联
        userDao.deleteUserRoleAssociation(userId);
        //添加新的user-role关联
        this.setUserRoleAssociation(userId,roleIds);
    }

    @Override
    public void delete(Integer id) {
        //删除user-role关联
        userDao.deleteUserRoleAssociation(id);
        //删除user
        userDao.delete(id);
    }




    @Override
    public List<Menu> findUserMenus(String username) {
        //1.得到用户的username
        User user = userDao.findByUsername(username);
        if(user==null){
            return null;
        }
        Integer userId = user.getId();
        //2.通过username得到用户信息，再通过用户id查询对应的角色信息（角色信息假设可以有多个）
        Set<Role> roles = roleDao.findByUserId(userId);
        //3.通过角色id查询角色对应的菜单信息
        Map<Integer,Menu> parentMap=new HashMap<>();//map目的为了去除重复菜单信息，得到当前用户对应所有角色的菜单信息
        for (Role role : roles) {
            Integer roleId = role.getId();
            //当前角色id对应的所有的菜单信息
            LinkedHashSet<Menu> allMenus = menuDao.findByRoleId(roleId);
            for (Menu allMenu : allMenus) {
                //6.若角色有多个角色信息，则根据不同角色id查询出来的菜单信息进行拼接去重操作
                parentMap.put(allMenu.getId(),allMenu);
            }
        }

        Set<Integer> keys = parentMap.keySet();
        List<Menu> menus=new ArrayList<>();
        for (Integer key : keys) {
            Menu menu = parentMap.get(key);//得到所有的菜单
            Integer menuId = menu.getId();//父菜单id
            //4.根据查询出来的菜单信息去查询对应的子菜单信息
            List<Menu> childrenMenus = menuDao.findChildrenByPrentMenuId(menuId);
            if(childrenMenus!=null&&childrenMenus.size()>0){//当前父菜单有子菜单
                //5.将子菜单信息加入到父菜单信息中去
                menu.setChildren(childrenMenus);
            }
            menus.add(menu);
        }
        //判断一下menus中的menu是否有子菜单，没有就删除
        for (int i = 0; i < menus.size(); i++) {
            List<Menu> children = menus.get(i).getChildren();
            if(children.size()==0){
                menus.remove(i);
                i--;
            }
        }
//        {"id":6,"name":"预约列表","linkUrl":"ordersettinglist.html","path":"/3-1","priority":1,"description":null,"icon":null,"roles":[],"children":[],"parentMenuId":5,"level":2},
        //添加工作台
        Menu menu=new Menu();
        menu.setId(28);
        menu.setName("工作台");
        menu.setPath("1");
        menu.setLinkUrl("platform.html");
        menu.setIcon("fa-home");
        menu.setPriority(0);
        menu.setLevel(1);
        menus.add(0,menu);
        //7.将最后的菜单信息传递到前端页面展示
        return menus;
    }

    @Override
    public boolean checkName(String username) {
        Integer i = userDao.checkName(username);
        if(i==0){
            return false;
        }
        return true;
    }


    //添加用户-角色关联方法
    private void setUserRoleAssociation(Integer userId, Integer[] roleIds) {
        if(roleIds!=null&&roleIds.length>0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map=new HashMap<>();
                map.put("userId",userId);
                map.put("roleId",roleId);
                userDao.setUserRoleAssociation(map);
            }
        }
    }
}
